<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>5-14 马赛克2</title>
</head>

<body>
  <canvas id="c" width="700" height="300" style="border: 1px solid #ccc;"></canvas>

  <script>
    const context = document.getElementById('c')
    const ctx = context.getContext('2d')

    const img = new Image()
    img.src = '../images/dog.jpg'
    img.crossOrigin = ''

    img.onload = () => {
      ctx.drawImage(img, 10, 10)

      let imgData = ctx.getImageData(10, 10, img.width, img.height)
      let data = imgData.data

      const blur = 6 // 马赛克范围
      const blurR = 2 * blur + 1
      const total = blurR * blurR

      for (let i = blur; i <= img.width; i = i + blurR) {
        for (let j = blur; j <= img.height; j = j + blurR) {
          let r = 0
          let g = 0
          let b = 0
          for (let leny = -blur; leny <= blur; leny++) {
            for (let lenx = -blur; lenx <= blur; lenx++) {
              r += data[4 * ((j + leny) * img.width + i + lenx) + 0]
              g += data[4 * ((j + leny) * img.width + i + lenx) + 1]
              b += data[4 * ((j + leny) * img.width + i + lenx) + 2]
            }
          }

          let vr = r / total
          let vg = g / total
          let vb = b / total
          for (let leny = -blur; leny <= blur; leny++) {
            for (let lenx = -blur; lenx <= blur; lenx++) {
              data[4 * ((j + leny) * img.width + i + lenx) + 0] = vr
              data[4 * ((j + leny) * img.width + i + lenx) + 1] = vg
              data[4 * ((j + leny) * img.width + i + lenx) + 2] = vb
            }
          }
        }
      }

      ctx.putImageData(imgData, imgData.width + 30, 10)
    }
  </script>
</body>

</html>